import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-05-18
 * Time: 22:53
 */
public class TestUdpEchoClient {
    private DatagramSocket socket = null;
    private String severIP;
    private int severPort;

    public TestUdpEchoClient(String severIP,int severPort) throws SocketException {
        // 客户端不指定端口号，系统自动分配
        socket = new DatagramSocket();
        this.severIP = severIP;
        this.severPort = severPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner sc = new Scanner(System.in);
        // 客户端不断发送接收
        while (true) {
            System.out.print("请输入请求：");
            String request = sc.next();
            // 1. 客户端发送请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(severIP),severPort);
            socket.send(requestPacket);
            // 2. 接收服务器返回响应
            DatagramPacket reponsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(reponsePacket);
            // 打印响应信息
            String reponse = new String(reponsePacket.getData(),0, reponsePacket.getLength());
            System.out.printf("request:%s reponse:%s\n",request,reponse);
        }
    }

    public static void main(String[] args) throws IOException {
        TestUdpEchoClient testUdpEchoClient = new TestUdpEchoClient("127.0.0.1",9090);
        testUdpEchoClient.start();
    }

}
